//
//  GHMineOrderViewController.m
//  GodHorses
//
//  Created by Mac on 2017/11/17.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "GHMineOrderViewController.h"
#import "STSegementButton.h"
#import "GHOrderTableViewCell.h"
#import "GHOrderModel.h"
#import "GHNoResultView.h"
#import "GHOrderHeaderView.h"
#import "GHOrderFooterView.h"
#import "GHCoomentViewController.h"
@interface GHMineOrderViewController ()
@property(nonatomic, strong) NSArray                               *titleArray;
@property(nonatomic, strong) NSMutableArray<GHOrderModel*>                     *dataSouce;
@property(nonatomic, strong) STSegementButton                     *segementButton;
@property(nonatomic, assign) NSInteger                              page;//当前页
@property(nonatomic, strong) GHNoResultView                     *noResultView;//无数据
@end

@implementation GHMineOrderViewController


#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    _titleArray = @[@"全部",@"待付款",@"待发货",@"待收货",@"待评价",@"已完成"];
    self.title = @"我的订单";
    [self configSubView];
    
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;

    self.segementButton = [[STSegementButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 44)
                                                         andTitle:_titleArray handle:^(STSegementButton *sender) {
                                                             weakSelf.currentTitle = weakSelf.titleArray[sender.tag];
                                                             [weakSelf.tableView.mj_header beginRefreshing];
                                                         }];
    self.segementButton.backgroundColor = [UIColor whiteColor];
    self.segementButton.lineSelectedColor = GH_YellowBackGroundColor;
    self.segementButton.butTitleSelectedColor = GH_YellowBackGroundColor;
    self.segementButton.butTitleColor = GH_firstTextColor;
    self.segementButton.lineColor = [UIColor whiteColor];
    NSInteger num = [_titleArray indexOfObject:self.currentTitle];
    self.segementButton.cureentIndex = num;
    
    self.segementButton.autoMoveWithClic = YES;
    [self.view addSubview:self.segementButton];

    self.tableView.st_top = self.tableView.st_top + 44;
    self.tableView.st_height =  self.tableView.st_height - 44;
    //无数据view
    self.noResultView = [[GHNoResultView alloc] initWithFrame:CGRectMake(0, 100, UIScreenWidth, 350) title:@"暂无订单" buttonTitle:@"快去购买商品吧" buttonHandle:^(NSString *titleString) {
        
    }];
    self.noResultView.hidden = YES;
    [self.tableView addSubview:self.noResultView];
    //header
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self sendRequetsWithPage:self.page];
    }];

    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page = self.page + 1 ;
        [self sendFooterRequetsWithPage:self.page];
    }];
//    self.tableView.mj_footer.hidden = YES
    //注册重用
    [self.tableView registerClass:[GHOrderHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.tableView registerClass:[GHOrderFooterView class] forHeaderFooterViewReuseIdentifier:@"footer"];
    [self.tableView registerClass:[GHOrderTableViewCell class] forCellReuseIdentifier:@"cell"];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce[section].goodList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [GHOrderTableViewCell CellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return [GHOrderHeaderView headerHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return [GHOrderFooterView footerHeight];
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    GHOrderHeaderView * header = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    header.model = self.dataSouce[section];
    return header;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    GHOrderFooterView * footer = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer"];
    footer.model = self.dataSouce[section];
    __weak typeof(self) weakSelf =  self;
    __weak typeof(footer) weakFooter =  footer;
    [footer.jifenButton setClicAction:^(UIButton *sender) {
        sender.selected = !sender.selected;
        weakFooter.model.jifenSelected = !weakFooter.model.jifenSelected;
      //  [weakSelf reloadData];
    }];
    [footer.shenmaPayButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedShenmaButtonWithSection:section];
    }];

    [footer.payButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedpayButtonWithSection:section canJifen:weakFooter.jifenButton.selected];
    }];
    [footer.cancleButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedCancleButtonWithISection:section];
    }];
    [footer.shouhuoButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedShouhuoWithSection:section];
    }];
    [footer.pingjiaButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedPingjiaWithSection:section];
    }];
    return footer;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    GHOrderTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.model = self.dataSouce[indexPath.section].goodList[indexPath.row];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Action Method
- (void)onSlectedCancleButtonWithISection:(NSInteger)section{
    [self showAlertCancelAndConfirm:@"你确定要删除该订单吗？" andWithBlock:^(NSString *name) {
        if ([name isEqualToString:@"确认"]) {
            [self sendCancleRequestWithSection:section];
        }
    }];
}
//余额支付
- (void)onSlectedpayButtonWithSection:(NSInteger)section canJifen:(BOOL)canJifen{
     GHOrderModel * model = self.dataSouce[section];
    NSString * money = model.order_amount;
    if (model.jifenSelected) {
        money = @(money.floatValue - model.can_jifen.floatValue).description;
    }
   
    [self showAlertCancelAndConfirm: [NSString stringWithFormat:@"你将要余额支付%@元",money] andWithBlock:^(NSString *name) {
        if ([name isEqualToString:@"确认"]) {
            [self sendYuePayRequestWithRequest:section canJifen:canJifen];
        };
    }];
    
}
//神马支付
- (void)onSlectedShenmaButtonWithSection:(NSInteger)section{
    
    GHOrderModel * model = self.dataSouce[section];
    NSString * money = model.order_amount;
    [self showAlertCancelAndConfirm: [NSString stringWithFormat:@"你将要神马值支付%@元",money] andWithBlock:^(NSString *name) {
        if ([name isEqualToString:@"确认"]) {
              [self sendShenmaPayRequestWithRequest:section];
        };
    }];
  
}
//待收货
- (void)onSlectedShouhuoWithSection:(NSInteger)section{
    [self showAlertCancelAndConfirm:@"你确定要确认收货吗？" andWithBlock:^(NSString *name) {
        if ([name isEqualToString:@"确认"]) {
            [self sendConfimShouhuoRequestWithSection:section];
        }
    }];
}
//待评价
- (void)onSlectedPingjiaWithSection:(NSInteger)section{
    GHCoomentViewController * vc = [GHCoomentViewController new];
    vc.model = self.dataSouce[section];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --Private Method
- (void)reloadData{
    
    self.noResultView.hidden = self.dataSouce.count;
    [self.tableView reloadData];
}
- (void)dealOrderDataWithDic:(NSDictionary*)responseObject fromHeader:(BOOL)fromHeader{

    if (fromHeader) {
        self.dataSouce = [NSMutableArray new];
    }
    NSDictionary * dataDic = responseObject[@"data"];
    if ([dataDic.allKeys containsObject:@"total_page"]) {
        NSInteger total_page = [dataDic[@"total_page"] integerValue];
        if (fromHeader) {//header 的刷新
            if (total_page > 1) {
            }
        }

    }
    //获取订单数组
    if ([dataDic.allKeys containsObject:@"order_info"]) {
        NSArray * orderDics = dataDic[@"order_info"];
        for (NSDictionary * orderDic in orderDics) {
            GHOrderModel *  model = [GHOrderModel mj_objectWithKeyValues:orderDic];
            model.jifenSelected =  YES;
            if ([dataDic.allKeys containsObject:@"order_type"]) {
                //订单类型
                NSInteger order_type = [dataDic[@"order_type"] integerValue];
                model.order_type = order_type;
            }
            [self.dataSouce addObject:model];
        }
        
    }

    [self reloadData];
    
}
#pragma mark --NetWork Method
//获取该类型下的订单
- (void)sendRequetsWithPage:(NSInteger)page{
    //[SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    [dic setObject:@(page) forKey:@"page"];
    //-1获取全部订单0待支付订单1待发货订单2待收货订单3待评价订单4已完成订单
    NSString * type = @"-1";
    if ([self.currentTitle isEqualToString:@"待付款"]) {
        type = @"0";
    }
    if ([self.currentTitle isEqualToString:@"待发货"]) {
        type = @"1";
    }
    if ([self.currentTitle isEqualToString:@"待收货"]) {
        type = @"2";
    }
    if ([self.currentTitle isEqualToString:@"待评价"]) {
        type = @"3";
    }
    if ([self.currentTitle isEqualToString:@"已完成"]) {
        type = @"4";
    }
    [dic setObject:type forKey:@"order_type"];
    
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/order/get_my_orders"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [self.tableView.mj_header endRefreshing];
                                                 self.tableView.mj_footer.hidden = NO;
                                                 [self dealOrderDataWithDic:responseObject fromHeader:YES ];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 self.dataSouce = [NSMutableArray new];
                                                 self.tableView.mj_footer.hidden = YES;
                                                 [self reloadData];
                                             }];
}
//mj-footer action
- (void)sendFooterRequetsWithPage:(NSInteger)page{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    [dic setObject:@(page) forKey:@"page"];
    //-1获取全部订单0待支付订单1待发货订单2待收货订单3待评价订单4已完成订单
    NSString * type = @"-1";
    if ([self.currentTitle isEqualToString:@"待付款"]) {
        type = @"0";
    }
    if ([self.currentTitle isEqualToString:@"待发货"]) {
        type = @"1";
    }
    if ([self.currentTitle isEqualToString:@"待收货"]) {
        type = @"2";
    }
    if ([self.currentTitle isEqualToString:@"待评价"]) {
        type = @"3";
    }
    if ([self.currentTitle isEqualToString:@"已完成"]) {
        type = @"4";
    }
    [dic setObject:type forKey:@"order_type"];
    
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/order/get_my_orders"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [self.tableView.mj_footer endRefreshing];
                                                 [self dealOrderDataWithDic:responseObject fromHeader:NO];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 if ([error.desc isEqualToString:@"暂无数据"]) {
                                                     [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                                 }else{
                                                     [self.tableView.mj_footer endRefreshing];
                                                     [SVProgressHUD showErrorWithStatus:error.desc];
                                                 }
                                                 [self reloadData];
                                             }];
}
//取消订单请求
- (void)sendCancleRequestWithSection:(NSInteger)section{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    GHOrderModel * model = self.dataSouce[section];
    if (model.oriderID.length) {
        [dic setObject:model.oriderID forKey:@"o_id"];
    }else{
        NSLog(@"订单id不能为空");
        return;
    }
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/order/cancel_order"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"取消订单成功"];
                                                 [self.dataSouce removeObjectAtIndex:section];
                                                 [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
                                                 [self.tableView.mj_header beginRefreshing];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
//确认收货请求
- (void)sendConfimShouhuoRequestWithSection:(NSInteger)section{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    GHOrderModel * model = self.dataSouce[section];
    if (model.oriderID.length) {
        [dic setObject:model.oriderID forKey:@"o_id"];
    }else{
        NSLog(@"订单id不能为空");
        return;
    }
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/order/order_confirm"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"确认收货成功"];
                                                 [self.tableView.mj_header beginRefreshing];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
//神马值支付
- (void)sendShenmaPayRequestWithRequest:(NSInteger)section{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    GHOrderModel * model = self.dataSouce[section];
    if (model.oriderID.length) {
        [dic setObject:model.oriderID forKey:@"o_id"];
    }else{
        NSLog(@"订单id不能为空");
        return;
    }
    //计算总金额
    NSInteger num = 0;
    CGFloat allPrice = 0;
    for (GHOrderGoodModel * good in model.goodList) {
        num = num + [good.g_num integerValue];
        allPrice = allPrice + [good.total_price floatValue];
    }
    if (allPrice) {
         [dic setObject:@(allPrice) forKey:@"money"];
    }else{
          [SVProgressHUD showErrorWithStatus:@"订单金额有误"];
        return;
    }
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/cash/sm_pay"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"神马值支付成功"];
                                                 [self.tableView.mj_header beginRefreshing];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
//余额支付
- (void)sendYuePayRequestWithRequest:(NSInteger)section canJifen:(BOOL)canJifen{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    GHOrderModel * model = self.dataSouce[section];
    if (model.oriderID.length) {
        [dic setObject:model.oriderID forKey:@"o_id"];
    }else{
        NSLog(@"订单id不能为空");
        return;
    }
    if (model.jifenSelected) {
        [dic setObject:model.can_jifen forKey:@"jifen"];
    }
    //计算总金额
    NSInteger num = 0;
    CGFloat allPrice = 0;
    for (GHOrderGoodModel * good in model.goodList) {
        num = num + [good.g_num integerValue];
        allPrice = allPrice + [good.total_price floatValue];
    }
    if (allPrice) {
        [dic setObject:@(allPrice) forKey:@"money"];
    }else{
        [SVProgressHUD showErrorWithStatus:@"订单金额有误"];
        return;
    }
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/cash/balance_pay"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"余额支付成功"];
                                                 [self.tableView.mj_header beginRefreshing];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end
